﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using System;
using System.Collections;
using System.Collections.Generic;
using Tesla.Util;

namespace Tesla.Graphics {
    /// <summary>
    /// Standard render bucket used by default. Contains a list of Spatials
    /// which it will use the engine's implementation of merge sort when sorting.
    /// </summary>
    public class RenderBucket : IRenderBucket {
        private IRenderer _renderer;
        private IRenderBucketComparer _comparer;

        //Actual bucket list
        private IRenderable[] _currentList;
        private IRenderable[] _tempList;
        private int _currentListCount;

        /// <summary>
        /// Gets the current number of renderables contained in the bucket.
        /// </summary>
        public int Count {
            get {
                return _currentListCount;
            }
        }

        /// <summary>
        /// Gets the renderable at the given index in the bucket.
        /// </summary>
        /// <param name="index">Zero-based index</param>
        /// <returns>The renderable at the index, if it exists</returns>
        public IRenderable this[int index] {
            get {
                if(index > _currentList.Length) {
                    throw new ArgumentOutOfRangeException("Index out of range.");
                }
                return _currentList[index];
            }
        }

        /// <summary>
        /// Gets the current renderer assigned to this render bucket.
        /// </summary>
        public IRenderer Renderer {
            get {
                return _renderer;
            }
        }

        /// <summary>
        /// Gets the bucket comparer owned by this bucket.
        /// </summary>
        public IRenderBucketComparer BucketComparer {
            get {
                return _comparer;
            }
        }

        /// <summary>
        /// Creates a new RenderBucket.
        /// </summary>
        /// <param name="renderer">Renderer to use</param>
        /// <param name="comparer">Renderable comparer to use</param>
        public RenderBucket(IRenderer renderer, IRenderBucketComparer comparer) {
            _renderer = renderer;
            _comparer = comparer;

            _currentList = new IRenderable[32];
            _currentListCount = 0;
        }

        /// <summary>
        /// Adds a renderable to the bucket.
        /// </summary>
        /// <param name="renderable">Renderable to add</param>
        public void Add(IRenderable renderable) {
            //Resize array if needed
            if(_currentListCount == _currentList.Length) {
                IRenderable[] temp = new IRenderable[_currentListCount * 2];
                Array.Copy(_currentList, temp, _currentListCount);
                _currentList = temp;
            }
            _currentList[_currentListCount++] = renderable;
        }

        /// <summary>
        /// Removes a renderable from the bucket.
        /// </summary>
        /// <param name="renderable">Renderable to remove</param>
        public void Remove(IRenderable renderable) {
            int index = 0;
            bool found = false;
            //Search array until the offending spatial is found
            for(int i = 0; i < _currentListCount; i++) {
                if(_currentList[index] == renderable) {
                    found = true;
                    break;
                }
                index++;
            }

            if(!found) {
                return;
            }

            Array.Copy(_currentList, index + 1, _currentList, index, _currentListCount - 1);

            _currentListCount--;
        }

        /// <summary>
        /// Clears all renderables from the bucket.
        /// </summary>
        public void Clear() {
            Array.Clear(_currentList, 0, _currentListCount);
            if(_tempList != null) {
                Array.Clear(_tempList, 0, _tempList.Length);
            }
            _currentListCount = 0;
        }

        /// <summary>
        /// Renders all renderables in the bucket.
        /// </summary>
        public virtual void Render() {
            for(int i = 0; i <_currentListCount; i++) {
                IRenderable renderable = _currentList[i];
                if(renderable != null) {
                    renderable.Render(_renderer);
                }
            }
        }

        /// <summary>
        /// Sorts all renderables in the bucket.
        /// </summary>
        public void Sort() {
            //Where the magic happens
            if(_currentListCount > 1) {
                //Clone if null or length is less than our current list
                if(_tempList == null || _tempList.Length < _currentList.Length) {
                    _tempList = (IRenderable[]) _currentList.Clone();
                } else {
                    Array.Copy(_currentList, _tempList, _currentListCount);
                }

                //Merge sort
                SortHelper.MergeSort<IRenderable>(_tempList, _currentList, 0, _currentListCount, 0, _comparer);
            }
        }

        /// <summary>
        /// Returns the render bucket's enumerator.
        /// </summary>
        /// <returns>Enumerator</returns>
        public IEnumerator<IRenderable> GetEnumerator() {
            return (IEnumerator<IRenderable>) _currentList.GetEnumerator();
        }

        IEnumerator System.Collections.IEnumerable.GetEnumerator() {
            return _currentList.GetEnumerator();
        }

    }
}
